<template>
  <el-collapse-item name="members">
    <div class="top" slot="title">
      <PartitionTitle title="人员安排" type="line"></PartitionTitle>
    </div>
    <el-table
      :data="list"
      show-summary
      :summary-method="getSummaries"
      tooltip-effect="dark"
      :span-method="handleSpanMethod"
      border
      style="width: 100%"
    >
      <el-table-column label="工位" prop="workStationName">
        <template slot-scope="{ row }">
          <span>{{ row.workStationName }}</span>
          <!-- 接班或交班时以及非产线负责人，才可以新增 -->
          <el-button
            v-if="['1', '2'].includes(status) && row.workStationId"
            type="text"
            @click="handleAddMembers(row)"
            >新增</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="人员" prop="realname">
        <template slot-scope="{ row }">
          <span>{{
            row.username ? `${row.realname}(${row.username})` : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="属性" prop="identity">
        <template slot-scope="{ row }">
          {{ identityMap[row.identity] || "" }}
        </template>
      </el-table-column>
      <el-table-column v-if="['2', '3'].includes(status)" label="生产小时数">
        <template slot-scope="{ row }">
          <el-input-number
            v-if="status === '2'"
            v-model="row.workHours"
            size="small"
            @change="handleWorkhoursChange"
          ></el-input-number>
          <span v-else>{{ row.workHours }}</span>
        </template>
      </el-table-column>
      <!-- 接班以及非产线负责人，才可以删除 -->
      <el-table-column v-if="status == '1'" label="操作" width="80">
        <template slot-scope="{ row }">
          <el-button
            v-if="row.workStationId"
            type="text"
            @click="handleDeleteMembers(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 人员列表 -->
    <userList
      :visibles.sync="userDialog.visible"
      :multiple="true"
      :defaultValues="userDialog.defaultLineUsers"
      :branchinnercode="userDialog.branchinnercode"
      @closeDialog="closeUserDialog"
    ></userList>
  </el-collapse-item>
</template>
<script>
import { getStationUserInfos } from "@/api/shifts/turnOnDuty";
import { mapState, mapMutations } from "vuex";
export default {
  props: {
    // 表单状态，控制不同情况下 表单呈现的效果，1-接班，2-交班，3-历史查看，4-查看班组
    status: {
      type: String,
      default: "1",
    },
    detailKey: {
      type: String,
      default: "takeoverDetail",
    },
  },
  dicts: ["identity"],
  data() {
    return {
      list: [],
      userDialog: {
        visible: false,
        defaultLineUsers: [],
        branchinnercode: null,
        row: null,
      },
    };
  },
  computed: {
    ...mapState({
      takeoverDetail: (state) => state.turnOnDuty.takeoverDetail,
      handoverDetail: (state) => state.turnOnDuty.handoverDetail,
    }),
    detailsData() {
      return this[this.detailKey];
    },
    identityMap() {
      return this.dictToMap(this.dict.identity);
    },
    count() {
      let result = {
        menberCount: 0,
        workHoursCount: 0,
      };
      if (!this.list?.length) {
        return result;
      }
      let usernames = [];
      let hours = 0;
      this.list.forEach((ele) => {
        if (ele.username && !usernames.includes(ele.username)) {
          usernames.push(ele.username);
        }
        if (ele.workHours) {
          hours += Number(ele.workHours);
        }
      });
      result.menberCount = usernames.length;
      result.workHoursCount = hours.toFixed(2);
      return result;
    },
  },
  created() {},
  mounted() {
    this.getMembersDetails();
  },
  methods: {
    ...mapMutations("turnOnDuty", [
      "SET_TAKEOVER_WORKSTATIONUSERVOS",
      "SET_HANDOVER_WORKSTATIONUSERVOS",
    ]),
    getSummaries() {
      const { menberCount, workHoursCount } = this.count;
      if (["1", "4"].includes(this.status)) {
        return ["合计", "", menberCount];
      }
      return ["合计", "", menberCount, workHoursCount];
    },
    handleSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 只有第一列工位需要做合并
      if (columnIndex == 0) {
        return {
          rowspan: row.rowspan,
          colspan: 1,
        };
      } else {
        return {
          rowspan: 1,
          colspan: 1,
        };
      }
    },
    // 获取工位人员
    getMembersDetails() {
      if (!this.detailsData) {
        return;
      }
      const param = {
        factoryDeptCode: this.detailsData.factoryDeptCode || null,
        workshopId: this.detailsData.workshopId || null,
        lineId: this.detailsData.lineId || null,
        groupId: this.detailsData.groupId || null,
        produceDate: this.detailsData.produceDate || null,
        takeoverManager: this.detailsData.takeoverManager || null,
        produceTimeDur: this.detailsData.produceTimeDur || null,
        orderDtos:
          this.detailsData.orderDtos?.map(({ id, itemCode, orderSn }) => ({
            id,
            itemCode,
            orderSn,
          })) || null,
        workshopType: this.detailsData.workshopType,
      };
      getStationUserInfos(param)
        .then((res) => {
          this.list = this.formatList(res.data) || [];
          this.updateMemberStore(res.data);
        })
        .catch(() => {
          this.list = [];
          this.updateMemberStore([]);
        });
    },
    // 格式化工位人员list
    formatList(data) {
      let result = [];
      data.forEach((ele) => {
        const len = ele.workStationUserHourVos?.length;
        if (len) {
          ele.workStationUserHourVos.forEach((user, index) => {
            result.push({ ...ele, ...user, rowspan: index == 0 ? len : 0 });
          });
        } else {
          result.push({ ...ele, rowspan: 1 });
        }
      });
      return result;
    },
    // 生产小时数修改
    handleWorkhoursChange() {
      if (!this.detailsData) {
        return;
      }
      let _workStationUserVos = this.detailsData.workStationUserVos || [];
      let _list = this.list;
      _workStationUserVos.forEach((ele) => {
        ele.workStationUserHourVos?.forEach((user) => {
          const item = _list.find(
            (row) =>
              row.workStationId == ele.workStationId &&
              row.username == user.username
          );
          if (item) {
            user.workHours = item.workHours;
          }
        });
      });
      this.updateMemberStore(_workStationUserVos);
    },
    // 增加人员
    handleAddMembers(row) {
      this.userDialog.defaultLineUsers =
        row.workStationUserHourVos?.map((ele) => ({
          username: ele.username,
          realname: ele.realname,
          userId: ele.userId,
          identity: ele.identity,
          workHours: ele.workHours,
        })) || [];
      this.userDialog.branchinnercode = this.detailsData?.factoryDeptId || null;
      this.userDialog.row = row;
      this.userDialog.visible = true;
    },
    closeUserDialog(list) {
      const row = this.userDialog.row;
      const data = [...this.detailsData.workStationUserVos] || [];
      const stationitem = data.find(
        (ele) => ele.workStationId == row.workStationId
      );
      if (!stationitem?.workStationUserHourVos) {
        stationitem.workStationUserHourVos = [];
      }

      stationitem.workStationUserHourVos = list.map((ele) => ({
        username: ele.username,
        realname: ele.realname,
        userId: ele.userId,
        identity: ele.identity,
        workHours: ele.workHours || 0,
      }));

      this.updateMemberStore(data);
      this.list = this.formatList(data);
    },
    // 删除人员
    handleDeleteMembers(row) {
      // 没有id说明是产线负责人，不能删除，没有username说明没有人可以删除
      if (!row?.workStationId || !row?.username) {
        return;
      }
      this.$confirm(`是否确认删除${row.realname}？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const data = [...this.detailsData.workStationUserVos] || [];
        const stationitem = data.find(
          (ele) => ele.workStationId == row.workStationId
        );
        if (stationitem?.workStationUserHourVos?.length) {
          stationitem.workStationUserHourVos =
            stationitem.workStationUserHourVos.filter(
              (ele) => ele.username != row.username
            );
        }
        this.updateMemberStore(data);
        this.list = this.formatList(data);
      });
    },
    // 更新store数据
    updateMemberStore(data) {
      if (this.detailKey == "takeoverDetail") {
        this.SET_TAKEOVER_WORKSTATIONUSERVOS(data);
      } else {
        this.SET_HANDOVER_WORKSTATIONUSERVOS(data);
      }
    },
  },
  watch: {
    "handoverDetail.produceTimeDur": {
      handler(newVal) {
        // 生产时长变更，则人员生产小时数随之变更，生产小时数=生产时长/个人所在工位数
        if (newVal) {
          const _list = this.list;
          this.list.forEach((row) => {
            // 查找当前工位外其他的工位数
            const num = _list.filter(
              (ele) =>
                ele.username == row.username &&
                ele.workStationId != row.workStationId
            ).length;
            row.workHours = this.toFix(newVal / (num + 1), 2);
          });
          this.handleWorkhoursChange();
        }
      },
      deep: true,
    },
    "detailsData.orderDtos": {
      handler(newVal) {
        this.getMembersDetails();
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.top {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 16px;
  margin: 20px 0 10px;
}
.block-title {
  margin-bottom: 0;
}
::v-deep .el-table--border .el-table__cell:first-child .cell {
  display: flex;
  justify-content: space-between;
}
</style>
